package com.example.logistics.service;

import com.example.logistics.controller.dto.CreateOrderRequest;
import com.example.logistics.entity.*;
import com.example.logistics.repository.CustomerOrderRepository;
import com.example.logistics.repository.WarehouseRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.OffsetDateTime;

@Service
@RequiredArgsConstructor
public class OrderService {

    private final CustomerOrderRepository orderRepository;
    private final WarehouseRepository warehouseRepository;

    @Transactional
    public CustomerOrder createOrder(CreateOrderRequest request) {
        Warehouse warehouse = warehouseRepository.findById(request.getWarehouseId())
                .orElseThrow(() -> new EntityNotFoundException("Warehouse not found"));

        CustomerOrder order = CustomerOrder.builder()
                .orderNumber(request.getOrderNumber())
                .status(OrderStatus.NEW)
                .createdAt(OffsetDateTime.now())
                .warehouse(warehouse)
                .build();

        request.getItems().forEach(i -> {
            OrderItem item = OrderItem.builder()
                    .order(order)
                    .sku(i.getSku())
                    .name(i.getName())
                    .quantity(i.getQuantity())
                    .build();
            order.getItems().add(item);
        });

        return orderRepository.save(order);
    }

    @Transactional
    public CustomerOrder updateStatus(Long orderId, OrderStatus status) {
        CustomerOrder order = orderRepository.findById(orderId)
                .orElseThrow(() -> new EntityNotFoundException("Order not found"));
        order.setStatus(status);
        order.setUpdatedAt(OffsetDateTime.now());
        return orderRepository.save(order);
    }
}


